#include "translate_list.h"
// 将10进制整型 IP 转成字符串，存放到 IP_str
// @param int IP
// @param string IP_str
void number_to_string(int IP, string &IP_str){
	IP_str = "";
	char middle;
	string dest_str;
	
	middle = IP%10 + 48;
	dest_str += middle;
	IP = IP/10;
	for(; IP > 0; IP = IP/10){
		middle = IP%10 + 48;
		dest_str += middle;	
	}
	for(int i = dest_str.length() - 1; i >= 0; i--){
		IP_str += dest_str[i];
	}
}
//队尾插入一个操作符
void translate_list::insert(int opt){
	three_address *temp = new three_address;
	temp->set(opt);
	list.push_back(*temp);
}
//队尾插入一个操作符  和  一个地址
void translate_list::insert(int opt, string address1){
	three_address *temp = new three_address;
	temp->set(opt, address1);
	list.push_back(*temp);
}
//队尾插入一个操作符  和  两个地址
void translate_list::insert(int opt, string address1, string address2){
	three_address *temp = new three_address;
	temp->set(opt, address1, address2);
	list.push_back(*temp);
}
//队尾插入一个操作符  和  三个地址
void translate_list::insert(int opt, string address1, string address2, string address3){
	three_address *temp = new three_address;
	temp->set(opt, address1, address2, address3);
	list.push_back(*temp);
}
//输出三地址码列表
void translate_list::display(){
	vector<three_address>::iterator it=list.begin();
	string opt;
	cout<<setw(5)<<"index"<<"    "<<setw(5)<<"opt"<<"    "<<setw(8)<<"address1"<<"   "<<setw(8)<<"address2"<<"    "<<setw(8)<<"address3"<<endl;
	for(int index = 0;it!=list.end();it++){
		cout<<setw(5)<<index<<"    ";
		switch((*it).opt){
			case 0:
				opt = "+";
				break;
			case 1:
				opt = "-";
				break;
			case 2:
				opt = "*";
				break;
			case 3:
				opt = "/";
				break;
			case 4:
				opt = "=";
				break;
			case 5:
				opt = "==";
				break;
			case 6:
				opt = ">";
				break;
			case 7:
				opt = "<";
				break;
			case 8:
				opt = ">=";
				break;
			case 9:
				opt = "<=";
				break;
			case 13:
				opt = "IF";
				break;
			case 20:
				opt = "INT";
				break;
			case 21:
				opt = "CHAR";
				break;
			case 22:
				opt = "FLAOT";
				break;
			case 717:
				opt = "END";
				break;
			case 26:
				opt = "GOTO";
				break;
		}
		cout<<setw(5)<<opt<<"    ";
		cout<<setw(8)<<(*it).address1<<"   "<<setw(8)<<(*it).address2<<"    "<<setw(8)<<(*it).address3<<endl;
		index++;
	}			
}
// 队尾插入一个跳转到IP的   GOTO指令
void translate_list::insert_goto(int IP){
	string IP_str;
	number_to_string(IP, IP_str);
	
	three_address *temp = new three_address;
	temp->set(GOTO, IP_str);
	list.push_back(*temp);
}
// 队尾插入一个 GOTO 指令   
void translate_list::insert_goto(){
	three_address *temp = new three_address;
	temp->set(GOTO);
	list.push_back(*temp);
}
// 在等待回填的栈中添加指令的位置，等待回填
void translate_list::insert_back_point(int IP_number){
	roll_back_stack.push_back(IP_number);
}
// 将跳转到 IP_number 的指令 回填到等待回填的栈顶元素 location 所指向的位置
void translate_list::back_to_fill(int IP_number){
	int location = roll_back_stack.back();
	roll_back_stack.pop_back(); 
	string IP_str;
	number_to_string(IP_number, IP_str);
	list.at(location).set(GOTO, IP_str);	
}
